//
// Created by root on 2/23/18.
//

#include <string.h>
#include "lexerengine.h"
#include "../premise/premise.h"

#define RULE_SEPARATOR    " or "
#define RULE_DELIMITER    " :: "
#define ORDER_DELIMITER    " > "

static String parse_pattern(Statement *s1, Statement *s2, void (*registerPattern)(String token, Queue *patterns)) {
    String name = strdup(extract_content(s1));
    String pattern = strdup(extract_content(s2));
    String *patterns = split_strings(pattern, RULE_SEPARATOR);
    String p = NULL;
    Pattern *pat = NULL;
    Queue *queue = init_queue();
    while (*patterns) {
        p = extract_string(*patterns);
        String *str = split_strings(p, RULE_DELIMITER);
        pat = init_pattern(*str, *(str + 1));
        enqueue(queue, pat);
        patterns++;
    }
    registerPattern(name, queue);
    return NULL;
}


String rule(Statement *s1, Statement *s2) {
    parse_pattern(s1, s2, register_rule);
    return NULL;
}

String group(Statement *s1, Statement *s2) {
    parse_pattern(s1, s2, register_group);
    return NULL;
}

String token(Statement *s1, Statement *s2) {
    String name = strdup(extract_content(s1));
    String pattern = extract_string(extract_content(s2));
    register_token(name, pattern);
    return NULL;
}

String lex(Statement *s) {
    String lex_orders = inner_string(strdup(extract_content(s)));
    globalFunny->lexOrders = split_strings(lex_orders, ORDER_DELIMITER);
    cache_patterns();
    return NULL;
}
